var express = require('express');
var router = express.Router();

const bodyParser = require('body-parser');
const sha = require("./sha1");

/* GET users listing. */
router.post('/getToken', bodyParser.json(), (req, res) => {
  // 检查用户名是否为空
  if (!req.body["userAccount"]
      || typeof req.body["userAccount"] != "string"
      || !req.body["userAccount"].length) {
    res.json({
      err: 1,
      message: '用户名为空'
    })
  }
  // 检查用户密码是否为空
  else if (!req.body["password"]
      || typeof req.body["password"] != "string"
      || !req.body["password"].length) {
    res.json({
      err: 1,
      message: '用户密码为空'
    })
  } else {
    // 构造Token
    let myDate = new Date();
    // 声明JWT，并声明hash为SHA1
    let headPart = {'type':'JWT','algorithm':'SHA1'};
    let headPart64 = (Buffer.from(JSON.stringify(headPart))).toString("base64");
    // 声明负载，用户名为userAccount，由a签发，向b授权，有效期30s（时间的单位是毫秒）
    let payloadPart = {'userAccount':req.body["userAccount"],'ori':'a','aim':'b','exp':myDate.getTime()+30000};
    let payloadPart64 = (Buffer.from(JSON.stringify(payloadPart))).toString("base64");
    // 由前两部分的base64加上“盐”（这里用一个字符串"ServerSecret"）经过Hash生成签名
    let signPart = headPart64 + payloadPart64 + (Buffer.from("ServerSecret")).toString("base64");
    let signPartCode = sha.b64_sha1(signPart);
    res.json({
      headPart: headPart64,
      payloadPart: payloadPart64,
      signPart: signPartCode
    })
  }
})

module.exports = router;